﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using IPR_StudyMeetingMrgSys.ViewModel;
using IPR_StudyMeetingMrgSys.Models;
using IPR_StudyMeetingMrgSys.Enums;
using IPR_StudyMeetingMrgSys.Extension;
using IPR_StudyMeetingMrgSys.BLL;
using IPR_StudyMeetingMrgSys.Model;
using Newtonsoft.Json;
using log4net;
using System.Reflection;
using System.Data;
using System.Web;
using System.IO;
using IPR_StudyMeetingMrgSys.Common;

namespace IPR_StudyMeetingMrgSys.Controllers
{
    /// <summary>
    /// 集团计划信息控制器
    /// </summary>
    public class CorpPlanController : ApiController
    {
        ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        // GET: api/CorpPlan
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET: api/CorpPlan/5
        public string Get(int id)
        {
            Model.CorpPlan memp = new Model.CorpPlan();
            memp = new BLL.CorpPlan().GetModel(id);
            return JsonConvert.SerializeObject(memp);
            //return "value";
        }
        /// <summary>
        /// 根据计划ID获取集团计划信息
        /// </summary>
        /// <param name="cpid"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/CorpPlan/GetCorpPlanDetail")]
        public IHttpActionResult GetCorpPlanDetail(int cpid)
        {
            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {
                DataTable dt = new BLL.CorpPlan().GetList("CPID="+cpid.ToString()).Tables[0];
                resultMsg.Info = dt.Rows.Count > 0 ? StatusCodeEnum.Success.GetEnumText() : "未获取到相应数据";
                resultMsg.Count = dt.Rows.Count;
                resultMsg.Data = dt;
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }

        // POST: api/CorpPlan
        /// <summary>
        /// 集团计划信息增加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/CorpPlan/Add")]
        public IHttpActionResult Add(VM_CorpPlan model)
        {
            log.Info(JsonConvert.SerializeObject(model));
            Model.CorpPlan target = new Model.CorpPlan();
            Type type1 = target.GetType();
            Type type2 = model.GetType();
            foreach (var mi in type2.GetProperties())
            {
                var des = type1.GetProperty(mi.Name);
                if (des != null)
                {
                    try
                    {
                        des.SetValue(target, mi.GetValue(model, null), null);
                    }
                    catch
                    { }
                }
            }
            target.CPID = new BLL.SysManage().GetMaxId("CorpPlan", "CPID");
            target.DesignUserID = LoginUser.UserInfo.UserID;
            target.DesignUserName = LoginUser.UserInfo.UserName;
            target.IsUse = 1;
            target.IsRelease = 1;
            target.IsCheck = 1;
            target.AddUserID = LoginUser.UserInfo.UserID;
            target.AddUserName = LoginUser.UserInfo.UserName;
           
            target.AddDateTime = DateTime.Now;

            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {
                BLL.CorpPlan bEmp = new BLL.CorpPlan();
                if (!bEmp.Exists(target.CPName))
                {
                    if (new IPR_StudyMeetingMrgSys.BLL.CorpPlan().Add(target)>0)
                    {
                        resultMsg.Info = "增加成功";
                        resultMsg.Count = 1;
                        resultMsg.Data = target.CPID;
                    }
                    else
                    {
                        resultMsg.Info = "增加失败";
                    }
                }
                else
                {
                    resultMsg.Info = "计划信息已经存在，请不要重复增加";
                }
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }



        [HttpPost]
        [Route("api/CorpPlan/AddAndFileUpload")]
        public IHttpActionResult AddAndFileUpload()
        {
            log.Info("开始文件上传，文件数：" + HttpContext.Current.Request.Files.Count.ToString());
            Res res = new Res();
            var file = HttpContext.Current.Request.Files.Count > 0 ? HttpContext.Current.Request.Files[0] : null;

            Model.CorpPlan target = new Model.CorpPlan();

            var CPID = HttpContext.Current.Request["CPID"].ToString();
            var CPName = HttpContext.Current.Request["CPName"].ToString();
            var StartDateTime = HttpContext.Current.Request["StartDateTime"].ToString();
            var EndDateTime = HttpContext.Current.Request["EndDateTime"].ToString();
            var CPDescribe = HttpContext.Current.Request["CPDescribe"].ToString();

            log.Info("开始文件上传:");
            var path = "";
            var fileName = "";
            var svrFilePathPlusName = "/uploads/" ;
            if (file != null && file.ContentLength > 0)
            {
                fileName = Path.GetFileName(file.FileName);
                if (!Directory.Exists(HttpContext.Current.Server.MapPath("~/uploads")))
                {
                    Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/uploads"));
                }
                path = Path.Combine(
                    HttpContext.Current.Server.MapPath("~/uploads"),
                    fileName
                );

                log.Info("开始文件上传:" + fileName);
                file.SaveAs(path);
            }
            log.Info("文件数" + HttpContext.Current.Request.Files.Count.ToString() + "=" + fileName + "-" + path);

            target.CPName = CPName;
            target.CPDescribe = CPDescribe;
            DateTime? myDT = new DateTime();
            if (string.IsNullOrEmpty(StartDateTime))
                myDT = null;
            else
                myDT = Convert.ToDateTime(StartDateTime);
            target.StartDateTime = myDT;


            if (string.IsNullOrEmpty(EndDateTime))
                myDT = null;
            else
                myDT = Convert.ToDateTime(EndDateTime);
            target.EndDateTime = myDT;
            target.CPID = new BLL.SysManage().GetMaxId("CorpPlan", "CPID");
            target.DesignUserID = LoginUser.UserInfo.UserID;
            target.DesignUserName = LoginUser.UserInfo.UserName;
            target.IsUse = 1;
            target.IsRelease = 1;
            target.IsCheck = 1;
            target.AddUserID = LoginUser.UserInfo.UserID;
            target.AddUserName = LoginUser.UserInfo.UserName;

            target.AddDateTime = DateTime.Now;
            target.AnnexName = fileName;
            target.AnnexUrl = svrFilePathPlusName+fileName;
            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {
                BLL.CorpPlan bEmp = new BLL.CorpPlan();
                //if (!bEmp.Exists(target.CPName))
                //{
                    if (new IPR_StudyMeetingMrgSys.BLL.CorpPlan().UpdateAnnex(CPID,target.AnnexName,target.AnnexUrl) > 0)
                    {
                        resultMsg.Info = "增加成功";
                        resultMsg.Count = 1;
                        resultMsg.Data = target.CPID;
                    }
                    else
                    {
                        resultMsg.Info = "增加失败";
                    }
                //}
                //else
                //{
                //    resultMsg.Info = "计划信息已经存在，请不要重复增加";
                //}
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }



            return Json(res);
        }

        // POST: api/CorpPlan
        /// <summary>
        /// 集团计划信息分页查找
        /// </summary>
        /// <param name="swhere">查询条件</param>
        /// <param name="page">页索引</param>
        /// <param name="limit">页大小</param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/CorpPlan/Search")]
        public IHttpActionResult Search(string swhere, int page, int limit)
        {
            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {
                int startindex = (page - 1) * limit + 1;
                int endindex = page * limit;
                if (!string.IsNullOrEmpty(swhere == null ? string.Empty : swhere.Trim()))
                {
                    Dictionary<string, string> jsonObject = JsonConvert.DeserializeObject<Dictionary<string, string>>(swhere);
                    swhere = string.Empty;
                    swhere = " IsUse=1 ";
                    foreach (var item in jsonObject)
                    {
                        if (item.Key == "CPName")
                        {
                            swhere += $" and CPName like '%{item.Value}%'";
                        }
                        if (item.Key == "CPDescribe")
                        {
                            swhere += $" and CPDescribe like '%{item.Value}%'";
                        }
                        if (item.Key == "StartDateTime")
                        {
                            if(!string.IsNullOrWhiteSpace(item.Value))
                            swhere += $" and StartDateTime >= CONVERT(datetime,'{item.Value}')";
                        }
                        if (item.Key == "EndDateTime")
                        {
                            if (!string.IsNullOrWhiteSpace(item.Value))
                                swhere += $" and EndDateTime <= CONVERT(datetime,'{item.Value}')";
                        }
                        //if (item.Key == "IsRelease")
                        //{
                        //    if (!string.IsNullOrWhiteSpace(item.Value))
                        //    {
                        //        swhere += $" and IsRelease = '{item.Value}'";
                        //    }
                        //}
                        if (item.Key == "IsCheck")
                        {
                            if (!string.IsNullOrWhiteSpace(item.Value))
                            {
                                swhere += $" and IsCheck = '{item.Value}'";
                            }
                        }
                        if (item.Key == "IsUse")
                        {
                            if (!string.IsNullOrWhiteSpace(item.Value))
                            {
                                swhere += $" and IsUse = '{item.Value}'";
                            }
                        }
                    }
                }
                int rowCount = 0;
                DataSet dsSearch = new IPR_StudyMeetingMrgSys.BLL.CorpPlan().GetListByPage(swhere, "CPID", startindex, endindex, out rowCount);
                resultMsg.Info = rowCount > 0 ? StatusCodeEnum.Success.GetEnumText() : "未获取到相应数据";
                resultMsg.Count = rowCount;
                resultMsg.Data = dsSearch.Tables[0];
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }

        /// <summary>
        /// 集团计划信息编辑
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/CorpPlan/Edit")]
        public IHttpActionResult Edit(Model.CorpPlan model)
        {
            log.Info(JsonConvert.SerializeObject(model));
 
 
            model.DesignUserID = LoginUser.UserInfo.UserID;
            model.DesignUserName = LoginUser.UserInfo.UserName;
            model.AddDateTime = DateTime.Now;
            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {
                if (new IPR_StudyMeetingMrgSys.BLL.CorpPlan().Update(model))
                {
                    resultMsg.Info = "编辑成功";
                    resultMsg.Count = 1;
                    resultMsg.Data = model.CPID;
                }
                else
                {
                    resultMsg.Info = "编辑失败";
                }
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }

        /// <summary>
        /// 集团计划信息删除(根据集团计划工号)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/CorpPlan/Del")]
        public IHttpActionResult Del(Model.CorpPlan model)
        {
            log.Info(JsonConvert.SerializeObject(model));

            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {
                if (new IPR_StudyMeetingMrgSys.BLL.CorpPlan().Delete(model.CPID))
                {
                    resultMsg.Info = "删除成功";
                    resultMsg.Count = 1;
                }
                else
                {
                    resultMsg.Info = "删除失败";
                }
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }
        #region 集团计划信息上传
        [HttpPost]
        [Route("api/CorpPlan/Upload")]
        public IHttpActionResult FileUpload()
        {
            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {
                var file = HttpContext.Current.Request.Files.Count > 0 ? HttpContext.Current.Request.Files[0] : null;
                if (file != null && file.ContentLength > 0)
                {
                    string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + Path.GetFileName(file.FileName);
                    string path = HttpContext.Current.Server.MapPath("~/UploadTemp");
                    Directory.CreateDirectory(path);
                    file.SaveAs(Path.Combine(path, fileName));
                    ExcelHelper excelHelper = new ExcelHelper(Path.Combine(path, fileName));
                    //sheet索引 和 列标题索引，第二个参数要特别注意，如果列标题在第二行，参数值传入为１
                    DataTable dataTable = excelHelper.ExcelToDataTable(0,1);
                    if (dataTable.Rows.Count == 0)
                    {
                        resultMsg.Info = "未获取到上传数据";
                        return Json(resultMsg);
                    }

                    foreach (DataRow dr in dataTable.Rows)
                    {
                        Model.CorpPlan mCp = new Model.CorpPlan();

                        mCp.CPID = long.Parse( dr[0].ToString());
                        mCp.CPName = dr[1].ToString();
                        mCp.CPDescribe = dr[2].ToString();
                        mCp.StartDateTime = String.IsNullOrWhiteSpace( dr[3].ToString())?DateTime.Parse("9999-12-31"):Convert.ToDateTime(dr[3].ToString());
                        mCp.EndDateTime = String.IsNullOrWhiteSpace(dr[4].ToString()) ? DateTime.Parse("9999-12-31") : Convert.ToDateTime(dr[4].ToString());
                        mCp.DesignUserName = dr[5].ToString();
                        mCp.IsRelease = 1;
                        mCp.IsUse = 1;
                        mCp.IsCheck = 1;
                        mCp.DesignUserID = LoginUser.UserInfo.UserID;
                        mCp.AddUserID = LoginUser.UserInfo.UserID;
                        mCp.AddUserName = LoginUser.UserInfo.UserName;
                        mCp.AddDateTime = DateTime.Now;
                        new BLL.CorpPlan().Add(mCp);
                    }
                    resultMsg.Info = "上传成功";
                    resultMsg.Count = dataTable.Rows.Count;
                }
                else
                {
                    resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                    resultMsg.Info = "部门不存在或上传的文件为空";
                }
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }
        /// <summary>
        /// 获取上传数据的试题类型
        /// </summary>
        /// <param name="ETName">试题类型名称</param>
        /// <returns></returns>
        private int GetUploadETID(string ETName)
        {
            switch (ETName)
            {
                case "选择":
                    return 1;
                case "判断":
                    return 2;
                case "填空":
                    return 3;
                case "简答":
                    return 4;
                case "综合":
                    return 5;
                default:
                    return 0;
            }
        }
        #endregion

        /// <summary>
        /// 计划信息删除(根据计划编号)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/CorpPlan/DelList")]
        public IHttpActionResult DelList(string delidlist)
        {
            log.Info(JsonConvert.SerializeObject(delidlist));

            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {
                var rows = new IPR_StudyMeetingMrgSys.BLL.CorpPlan().DeleteList(delidlist);
                if (rows>0)
                {
                    resultMsg.Info = "集团计划删除成功！" + rows + "条符合删除条件,已删除";
                    resultMsg.Count = 1;
                }
                else
                {
                    resultMsg.Info = "删除失败,删除0行(仅删除未审核未发布的计划)";
                }
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }

        /// <summary>
        /// 更新计划的状态，包含(审核、取消审核、发布、取消发布、使用、未使用)
        /// value 为0时表示取消审核/发布/使用中，为1时表未取消审核/取消发布/未使用
        /// </summary>
        /// <param name="mark">标记码，审核：C / 发布：R / 使用：U</param>
        /// <param name="value">1/0</param>
        /// <param name="wherevalue">条件，使用主键字段值 </param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/CorpPlan/UpdatePlanStatus")]
        public IHttpActionResult UpdatePlanStatus(string mark,string value,string wherevalue)
        {
            log.Info(JsonConvert.SerializeObject(mark+"="+value));

            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {
                string tablename = "CorpPlan";
                string fieldname = "";
                string fieldvalue = "";
                string wherefield = "CPID";
                if (mark == "C")
                {
                    fieldname = "IsCheck";
                }
                if (mark == "R")
                {
                    fieldname = "IsRelease";
                }
                if (mark == "U")
                {
                    fieldname = "IsUse";
                }
                fieldvalue = value;
                string ErrorMsg = string.Empty;
                new BLL.SysManage().ExecuteUpdate(tablename, fieldname, fieldvalue, wherefield, wherevalue, out ErrorMsg);
                if (string.IsNullOrEmpty(ErrorMsg))
                {
                    resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                    resultMsg.Info = "更新成功";
                    resultMsg.Count = 1;
                }
                else
                {
                    resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                    resultMsg.Info = ErrorMsg;
                }
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }

        // PUT: api/CorpPlan/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE: api/CorpPlan/5
        public void Delete(int id)
        {
        }
    }
}
